<template>
  <div class="realtime-test-page">
    <div class="page-header">
      <h1>实时通信测试</h1>
      <p>测试SignalR连接、房间管理和实时通信功能</p>
    </div>

    <!-- 添加画布同步测试 -->
    <div class="canvas-sync-test">
      <h3>画布同步测试</h3>
      <div class="test-controls">
        <el-button @click="connectToRoom" :disabled="isConnected" type="primary">
          连接到房间
        </el-button>
        <el-button @click="testPaintSync" :disabled="!isConnected" type="success">
          测试画布同步
        </el-button>
        <el-button @click="clearCanvas" type="warning">
          清空画布
        </el-button>
        <el-button @click="startAutoTest" :disabled="!isConnected || isAutoTesting" type="info">
          {{ isAutoTesting ? '停止自动测试' : '开始自动测试' }}
        </el-button>
      </div>
      
      <div class="canvas-comparison">
        <div class="canvas-section">
          <h4>本地画布</h4>
          <canvas
            ref="localCanvasRef"
            width="400"
            height="300"
            class="test-canvas local-canvas"
            @mousedown="startLocalDrawing"
            @mousemove="localDraw"
            @mouseup="stopLocalDrawing"
            @mouseleave="stopLocalDrawing"
          ></canvas>
          <div class="canvas-stats">
            <p>本地动作: {{ localActionsCount }}</p>
            <p>发送动作: {{ sentActionsCount }}</p>
          </div>
        </div>
        
        <div class="canvas-section">
          <h4>同步画布</h4>
          <canvas
            ref="syncCanvasRef"
            width="400"
            height="300"
            class="test-canvas sync-canvas"
          ></canvas>
          <div class="canvas-stats">
            <p>收到动作: {{ receivedActionsCount }}</p>
            <p>同步状态: {{ syncStatus }}</p>
          </div>
        </div>
      </div>
      
      <div class="sync-controls">
        <div class="control-group">
          <label>画笔大小:</label>
          <el-slider v-model="testBrushSize" :min="5" :max="30" size="small" />
        </div>
        <div class="control-group">
          <label>颜色:</label>
          <el-color-picker v-model="testColor" size="small" />
        </div>
        <div class="control-group">
          <label>工具:</label>
          <el-select v-model="testTool" size="small">
            <el-option label="画笔" value="brush" />
            <el-option label="橡皮擦" value="eraser" />
          </el-select>
        </div>
      </div>
      
      <div class="debug-info">
        <p>连接状态: {{ isConnected ? '已连接' : '未连接' }}</p>
        <p>房间ID: {{ testRoomId }}</p>
        <p>玩家ID: {{ testPlayerId }}</p>
        <p>收到的事件数量: {{ receivedEvents.length }}</p>
        <p>消息队列状态: {{ messageQueueStatus }}</p>
        <p>平均延迟: {{ averageLatency }}ms</p>
      </div>
      
      <div class="event-log">
        <h4>事件日志</h4>
        <div v-for="event in receivedEvents.slice(-10)" :key="event.id" class="event-item">
          <span class="event-time">{{ formatTime(event.timestamp) }}</span>
          <span class="event-type">{{ event.type }}</span>
          <span class="event-data">{{ JSON.stringify(event.data) }}</span>
        </div>
      </div>
    </div>

    <div class="main-content">
      <!-- 左侧房间管理 -->
      <div class="left-panel">
        <RoomManager />
      </div>

      <!-- 中间测试区域 -->
      <div class="center-panel">
        <div class="test-section">
          <h3>连接测试</h3>
          <div class="test-controls">
            <el-button @click="testPing" :disabled="!isConnected" type="primary">
              测试Ping
            </el-button>
            <el-button @click="testRoomInfo" :disabled="!currentRoom" type="info">
              获取房间信息
            </el-button>
            <el-button @click="testPaintAction" :disabled="!currentRoom" type="success">
              测试涂色动作
            </el-button>
          </div>
          
          <div class="test-results">
            <h4>测试结果</h4>
            <div class="result-item">
              <span>连接状态:</span>
              <span :class="connectionStatus">{{ getConnectionStatusText() }}</span>
            </div>
            <div class="result-item">
              <span>连接ID:</span>
              <span class="value">{{ connectionId || '未连接' }}</span>
            </div>
            <div class="result-item">
              <span>房间代码:</span>
              <span class="value">{{ currentRoom || '未加入房间' }}</span>
            </div>
            <div class="result-item">
              <span>玩家数量:</span>
              <span class="value">{{ playerCount }}</span>
            </div>
          </div>
        </div>

        <div class="test-section">
          <h3>实时涂色画布</h3>
          <div class="canvas-container">
            <canvas
              ref="canvasRef"
              width="400"
              height="300"
              class="paint-canvas"
              @mousedown="startDrawing"
              @mousemove="draw"
              @mouseup="stopDrawing"
              @mouseleave="stopDrawing"
            ></canvas>
            <div class="canvas-controls">
              <el-select v-model="currentTool" size="small">
                <el-option label="画笔" value="brush" />
                <el-option label="橡皮擦" value="eraser" />
              </el-select>
              <el-slider v-model="brushSize" :min="5" :max="30" size="small" />
              <el-color-picker v-model="currentColor" size="small" />
              <el-button @click="clearCanvas" size="small" type="danger">清空</el-button>
            </div>
          </div>
        </div>

        <div class="test-section">
          <h3>实时事件监控</h3>
          <div class="event-log" ref="eventLog">
            <div 
              v-for="event in eventLog" 
              :key="event.id"
              class="event-item"
              :class="event.type"
            >
              <div class="event-header">
                <span class="event-type">{{ event.type }}</span>
                <span class="event-time">{{ formatTime(event.timestamp) }}</span>
              </div>
              <div class="event-data">{{ JSON.stringify(event.data, null, 2) }}</div>
            </div>
          </div>
          <div class="event-controls">
            <el-button @click="clearEventLog" size="small" type="warning">
              清空日志
            </el-button>
            <el-button @click="exportEventLog" size="small" type="info">
              导出日志
            </el-button>
          </div>
        </div>
      </div>

      <!-- 右侧状态面板 -->
      <div class="right-panel">
        <div class="status-panel">
          <h3>系统状态</h3>
          
          <div class="status-section">
            <h4>连接信息</h4>
            <div class="status-item">
              <span>状态:</span>
              <span :class="connectionStatus">{{ getConnectionStatusText() }}</span>
            </div>
            <div class="status-item">
              <span>重连次数:</span>
              <span class="value">{{ reconnectCount }}</span>
            </div>
            <div class="status-item">
              <span>最后错误:</span>
              <span class="value error">{{ lastError || '无' }}</span>
            </div>
          </div>

          <div class="status-section">
            <h4>房间信息</h4>
            <div class="status-item">
              <span>房间代码:</span>
              <span class="value">{{ currentRoom || '未加入' }}</span>
            </div>
            <div class="status-item">
              <span>游戏状态:</span>
              <span class="value" :class="gameStatus">{{ getGameStatusText() }}</span>
            </div>
            <div class="status-item">
              <span>玩家数量:</span>
              <span class="value">{{ playerCount }}/8</span>
            </div>
            <div class="status-item">
              <span>是否为房主:</span>
              <span class="value">{{ isHost ? '是' : '否' }}</span>
            </div>
          </div>

          <div class="status-section">
            <h4>性能指标</h4>
            <div class="status-item">
              <span>消息数量:</span>
              <span class="value">{{ messageCount }}</span>
            </div>
            <div class="status-item">
              <span>平均延迟:</span>
              <span class="value">{{ averageLatency }}ms</span>
            </div>
            <div class="status-item">
              <span>最后更新:</span>
              <span class="value">{{ lastUpdateTime }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部状态栏 -->
    <div class="status-bar">
      <div class="status-item">
        <span>连接状态:</span>
        <span class="value" :class="connectionStatus">{{ getConnectionStatusText() }}</span>
      </div>
      <div class="status-item">
        <span>房间:</span>
        <span class="value">{{ currentRoom || '未加入' }}</span>
      </div>
      <div class="status-item">
        <span>玩家:</span>
        <span class="value">{{ playerCount }}/8</span>
      </div>
      <div class="status-item">
        <span>事件数量:</span>
        <span class="value">{{ eventLog.length }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useGameStore } from '@/stores/game'
import { createSignalRService } from '@/services/socketService'
import RoomManager from '@/components/RoomManager.vue'
import { ElMessage } from 'element-plus'

const gameStore = useGameStore()
const signalRService = createSignalRService(gameStore)

// 画布相关
const canvasRef = ref(null)
const ctx = ref(null)
const isDrawing = ref(false)
const lastX = ref(0)
const lastY = ref(0)

// 工具设置
const currentTool = ref('brush')
const brushSize = ref(10)
const currentColor = ref('#1890ff')

// 响应式数据
const eventLog = ref([])
const eventLogRef = ref(null)
const reconnectCount = ref(0)
const messageCount = ref(0)
const averageLatency = ref(0)
const lastUpdateTime = ref('--')

// 画布同步测试相关
const localCanvasRef = ref(null)
const syncCanvasRef = ref(null)
const testRoomId = ref('test-room-123')
const testPlayerId = ref('test-player-' + Math.random().toString(36).substr(2, 9))
const receivedEvents = ref([])
const testIsDrawing = ref(false)
const testLastX = ref(0)
const testLastY = ref(0)
const testBrushSize = ref(10)
const testColor = ref('#1890ff')
const testTool = ref('brush')
const isAutoTesting = ref(false)
const localActionsCount = ref(0)
const sentActionsCount = ref(0)
const receivedActionsCount = ref(0)
const syncStatus = ref('未同步')
const messageQueueStatus = ref('正常')

// 从store获取状态
const currentRoom = computed(() => gameStore.currentRoom)
const gameStatus = computed(() => gameStore.gameStatus)
const playerCount = computed(() => gameStore.playerCount)
const isConnected = computed(() => gameStore.isConnected)
const connectionStatus = computed(() => gameStore.connectionStatus)
const lastError = computed(() => gameStore.lastError)
const isHost = computed(() => gameStore.isHost)

// 计算属性
const connectionId = computed(() => signalRService.getConnectionId())

// 生命周期
onMounted(() => {
  initCanvas()
  setupEventListeners()
  startPerformanceMonitor()
})

onUnmounted(() => {
  stopPerformanceMonitor()
})

// 初始化画布
function initCanvas() {
  const canvas = canvasRef.value
  if (!canvas) return

  ctx.value = canvas.getContext('2d')
  ctx.value.fillStyle = '#ffffff'
  ctx.value.fillRect(0, 0, 400, 300)
}

// 开始绘制
function startDrawing(event) {
  isDrawing.value = true
  const rect = canvasRef.value.getBoundingClientRect()
  lastX.value = event.clientX - rect.left
  lastY.value = event.clientY - rect.top
}

// 绘制
function draw(event) {
  if (!isDrawing.value) return
  
  const rect = canvasRef.value.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top
  
  if (currentTool.value === 'brush') {
    ctx.value.strokeStyle = currentColor.value
    ctx.value.lineWidth = brushSize.value
    ctx.value.lineCap = 'round'
    ctx.value.beginPath()
    ctx.value.moveTo(lastX.value, lastY.value)
    ctx.value.lineTo(x, y)
    ctx.value.stroke()
  } else if (currentTool.value === 'eraser') {
    ctx.value.fillStyle = '#ffffff'
    ctx.value.beginPath()
    ctx.value.arc(x, y, brushSize.value / 2, 0, 2 * Math.PI)
    ctx.value.fill()
  }
  
  // 发送涂色动作
  sendPaintAction(x, y)
  
  lastX.value = x
  lastY.value = y
}

// 停止绘制
function stopDrawing() {
  isDrawing.value = false
}

// 发送涂色动作
function sendPaintAction(x, y) {
  if (!signalRService || !signalRService.getConnectionStatus() || !currentRoom.value) return
  
  const currentPlayerId = gameStore.currentPlayer?.id || 'unknown'
  
  signalRService.sendPaintAction(
    currentRoom.value,
    currentPlayerId,
    Math.round(x),
    Math.round(y),
    currentColor.value,
    brushSize.value,
    currentTool.value
  )
}

// 清空画布
function clearCanvas() {
  if (!ctx.value) return
  ctx.value.fillStyle = '#ffffff'
  ctx.value.fillRect(0, 0, 400, 300)
}

// 处理从其他玩家收到的涂色动作
function handlePaintActionReceived(paintData) {
  console.log('收到涂色动作:', paintData)
  
  const canvas = syncCanvasRef.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  // 避免处理自己的涂色动作
  if (paintData.PlayerId === testPlayerId.value) {
    console.log('跳过自己的涂色动作')
    return
  }
  
  const { X: x, Y: y, Tool: tool, Color: color, BrushSize: brushSize } = paintData
  
  console.log('绘制其他玩家的动作:', { x, y, tool, color, brushSize })
  
  // 根据工具类型绘制
  if (tool === 'brush') {
    ctx.fillStyle = color
    ctx.beginPath()
    ctx.arc(x, y, brushSize / 2, 0, 2 * Math.PI)
    ctx.fill()
    console.log('绘制了画笔动作')
  } else if (tool === 'eraser') {
    ctx.fillStyle = '#ffffff'
    ctx.beginPath()
    ctx.arc(x, y, brushSize / 2, 0, 2 * Math.PI)
    ctx.fill()
    console.log('绘制了橡皮擦动作')
  }
}

// 设置事件监听器
function setupEventListeners() {
  // 连接相关事件
  signalRService.on('Connected', (data) => {
    addEvent('Connected', data)
    updatePerformanceMetrics()
  })

  signalRService.on('Reconnecting', (data) => {
    addEvent('Reconnecting', data)
    reconnectCount.value++
  })

  signalRService.on('Reconnected', (data) => {
    addEvent('Reconnected', data)
    updatePerformanceMetrics()
  })

  signalRService.on('Disconnected', (data) => {
    addEvent('Disconnected', data)
  })

  // 房间相关事件
  signalRService.on('WelcomeMessage', (data) => {
    addEvent('WelcomeMessage', data)
  })

  signalRService.on('PlayerJoined', (data) => {
    addEvent('PlayerJoined', data)
    messageCount.value++
  })

  signalRService.on('PlayerLeft', (data) => {
    addEvent('PlayerLeft', data)
    messageCount.value++
  })

  signalRService.on('PlayerDisconnected', (data) => {
    addEvent('PlayerDisconnected', data)
    messageCount.value++
  })

  signalRService.on('GameStarted', (data) => {
    addEvent('GameStarted', data)
  })

  signalRService.on('GameEnded', (data) => {
    addEvent('GameEnded', data)
  })

  signalRService.on('PaintActionReceived', (data) => {
    addEvent('PaintActionReceived', data)
    messageCount.value++
    addReceivedEvent('PaintActionReceived', data)
    handlePaintActionReceived(data)
    receivedActionsCount.value++
  })

  signalRService.on('AreaUpdated', (data) => {
    addEvent('AreaUpdated', data)
    messageCount.value++
  })

  signalRService.on('ChatMessage', (data) => {
    addEvent('ChatMessage', data)
    messageCount.value++
  })

  signalRService.on('RoomStateUpdated', (data) => {
    addEvent('RoomStateUpdated', data)
  })

  signalRService.on('RoomInfo', (data) => {
    addEvent('RoomInfo', data)
  })

  signalRService.on('RoomNotFound', (data) => {
    addEvent('RoomNotFound', data)
  })

  signalRService.on('Pong', (data) => {
    addEvent('Pong', data)
    updatePerformanceMetrics()
  })

  signalRService.on('MaxReconnectAttemptsReached', (data) => {
    addEvent('MaxReconnectAttemptsReached', data)
  })
}

// 添加事件到日志
function addEvent(type, data) {
  const event = {
    id: Date.now() + Math.random(),
    type,
    data,
    timestamp: new Date()
  }
  
  eventLog.value.push(event)
  
  // 限制日志数量
  if (eventLog.value.length > 100) {
    eventLog.value.shift()
  }
  
  // 自动滚动到底部
  nextTick(() => {
    if (eventLogRef.value) {
      eventLogRef.value.scrollTop = eventLogRef.value.scrollHeight
    }
  })
}

// 测试Ping
async function testPing() {
  try {
    const startTime = Date.now()
    await signalRService.ping()
    const latency = Date.now() - startTime
    ElMessage.success(`Ping成功，延迟: ${latency}ms`)
  } catch (error) {
    ElMessage.error('Ping失败: ' + error.message)
  }
}

// 测试获取房间信息
async function testRoomInfo() {
  try {
    await signalRService.getRoomInfo(currentRoom.value)
    ElMessage.success('已请求房间信息')
  } catch (error) {
    ElMessage.error('获取房间信息失败: ' + error.message)
  }
}

// 测试涂色动作
async function testPaintAction() {
  try {
    const testData = {
      x: Math.floor(Math.random() * 800),
      y: Math.floor(Math.random() * 600),
      color: '#' + Math.floor(Math.random()*16777215).toString(16),
      brushSize: Math.floor(Math.random() * 20) + 5,
      tool: 'brush'
    }
    
    await signalRService.sendPaintAction(
      currentRoom.value,
      'test_player',
      testData.x,
      testData.y,
      testData.color,
      testData.brushSize,
      testData.tool
    )
    
    ElMessage.success('测试涂色动作已发送')
    addEvent('TestPaintAction', testData)
  } catch (error) {
    ElMessage.error('发送测试涂色动作失败: ' + error.message)
  }
}

// 清空事件日志
function clearEventLog() {
  eventLog.value = []
  ElMessage.info('事件日志已清空')
}

// 导出事件日志
function exportEventLog() {
  const dataStr = JSON.stringify(eventLog.value, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  
  const link = document.createElement('a')
  link.href = URL.createObjectURL(dataBlob)
  link.download = `event-log-${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.json`
  link.click()
  
  ElMessage.success('事件日志已导出')
}

// 性能监控
let performanceInterval = null

function startPerformanceMonitor() {
  performanceInterval = setInterval(() => {
    updatePerformanceMetrics()
  }, 5000) // 每5秒更新一次
}

function stopPerformanceMonitor() {
  if (performanceInterval) {
    clearInterval(performanceInterval)
    performanceInterval = null
  }
}

function updatePerformanceMetrics() {
  lastUpdateTime.value = new Date().toLocaleTimeString('zh-CN')
  
  // 计算平均延迟（这里简化处理）
  if (eventLog.value.length > 0) {
    const recentEvents = eventLog.value.slice(-10)
    const totalLatency = recentEvents.reduce((sum, event) => {
      return sum + (event.data?.Timestamp ? new Date(event.data.Timestamp).getTime() : 0)
    }, 0)
    averageLatency.value = Math.round(totalLatency / recentEvents.length)
  }
}

// 工具函数
function formatTime(timestamp) {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit',
    second: '2-digit'
  })
}

function getConnectionStatusText() {
  const statusMap = {
    disconnected: '未连接',
    connecting: '连接中...',
    connected: '已连接',
    reconnecting: '重连中...'
  }
  return statusMap[connectionStatus.value] || '未知'
}

function getGameStatusText() {
  const statusMap = {
    waiting: '等待中',
    playing: '游戏中',
    finished: '已结束'
  }
  return statusMap[gameStatus.value] || '未知'
}

// 画布同步测试方法
function connectToRoom() {
  console.log('连接到测试房间:', testRoomId.value)
  
  // 确保SignalR已连接
  if (!signalRService.getConnectionStatus()) {
    signalRService.connect()
  }
  
  // 加入测试房间
  signalRService.joinRoom(
    testRoomId.value,
    testPlayerId.value,
    '测试玩家',
    '#ff0000'
  )
  
  ElMessage.success('已连接到测试房间')
}

// 测试画布绘制方法
function startLocalDrawing(event) {
  testIsDrawing.value = true
  const rect = localCanvasRef.value.getBoundingClientRect()
  testLastX.value = event.clientX - rect.left
  testLastY.value = event.clientY - rect.top
  localActionsCount.value++
}

function localDraw(event) {
  if (!testIsDrawing.value) return
  
  const rect = localCanvasRef.value.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top
  
  const ctx = localCanvasRef.value.getContext('2d')
  ctx.strokeStyle = testColor.value
  ctx.lineWidth = testBrushSize.value
  ctx.lineCap = 'round'
  
  ctx.beginPath()
  ctx.moveTo(testLastX.value, testLastY.value)
  ctx.lineTo(x, y)
  ctx.stroke()
  
  // 发送涂色动作
  signalRService.sendPaintAction(
    testRoomId.value,
    testPlayerId.value,
    Math.round(x),
    Math.round(y),
    testColor.value,
    testBrushSize.value,
    testTool.value
  )
  
  testLastX.value = x
  testLastY.value = y
}

function stopLocalDrawing() {
  testIsDrawing.value = false
}

// 添加事件到接收列表
function addReceivedEvent(type, data) {
  const event = {
    id: Date.now() + Math.random(),
    type,
    data,
    timestamp: new Date()
  }
  
  receivedEvents.value.push(event)
  
  // 限制事件数量
  if (receivedEvents.value.length > 50) {
    receivedEvents.value.shift()
  }
}

function testPaintSync() {
  console.log('测试画布同步...')
  
  const testData = {
    x: Math.floor(Math.random() * 400),
    y: Math.floor(Math.random() * 300),
    color: '#' + Math.floor(Math.random()*16777215).toString(16),
    brushSize: Math.floor(Math.random() * 20) + 5,
    tool: 'brush'
  }
  
  signalRService.sendPaintAction(
    testRoomId.value,
    testPlayerId.value,
    testData.x,
    testData.y,
    testData.color,
    testData.brushSize,
    testData.tool
  )
  
  sentActionsCount.value++
  console.log('测试涂色动作已发送:', testData)
  ElMessage.success('测试涂色动作已发送')
}

// 自动测试功能
let autoTestInterval = null

function startAutoTest() {
  if (isAutoTesting.value) {
    stopAutoTest()
    return
  }
  
  isAutoTesting.value = true
  syncStatus.value = '自动测试中'
  
  autoTestInterval = setInterval(() => {
    if (!isAutoTesting.value) return
    
    const testData = {
      x: Math.floor(Math.random() * 400),
      y: Math.floor(Math.random() * 300),
      color: '#' + Math.floor(Math.random()*16777215).toString(16),
      brushSize: Math.floor(Math.random() * 20) + 5,
      tool: Math.random() > 0.8 ? 'eraser' : 'brush'
    }
    
    signalRService.sendPaintAction(
      testRoomId.value,
      testPlayerId.value,
      testData.x,
      testData.y,
      testData.color,
      testData.brushSize,
      testData.tool
    )
    
    sentActionsCount.value++
    
    // 在本地画布上也绘制
    const ctx = localCanvasRef.value?.getContext('2d')
    if (ctx) {
      if (testData.tool === 'brush') {
        ctx.fillStyle = testData.color
        ctx.beginPath()
        ctx.arc(testData.x, testData.y, testData.brushSize / 2, 0, 2 * Math.PI)
        ctx.fill()
      } else {
        ctx.fillStyle = '#ffffff'
        ctx.beginPath()
        ctx.arc(testData.x, testData.y, testData.brushSize / 2, 0, 2 * Math.PI)
        ctx.fill()
      }
    }
    
    localActionsCount.value++
    
  }, 1000) // 每秒发送一个动作
  
  ElMessage.success('自动测试已开始')
}

function stopAutoTest() {
  isAutoTesting.value = false
  syncStatus.value = '已停止'
  
  if (autoTestInterval) {
    clearInterval(autoTestInterval)
    autoTestInterval = null
  }
  
  ElMessage.info('自动测试已停止')
}

// 更新消息队列状态
function updateMessageQueueStatus() {
  const status = signalRService.getMessageQueueStatus()
  messageQueueStatus.value = `队列: ${status.queueLength}/${status.maxQueueSize}`
}

// 计算平均延迟
function calculateAverageLatency() {
  if (receivedEvents.value.length === 0) return 0
  
  const recentEvents = receivedEvents.value.slice(-20)
  let totalLatency = 0
  let count = 0
  
  recentEvents.forEach(event => {
    if (event.data?.Timestamp) {
      const eventTime = new Date(event.data.Timestamp).getTime()
      const receiveTime = new Date(event.timestamp).getTime()
      totalLatency += (receiveTime - eventTime)
      count++
    }
  })
  
  return count > 0 ? Math.round(totalLatency / count) : 0
}


</script>

<style scoped>
.realtime-test-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.page-header {
  text-align: center;
  color: white;
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  font-size: 36px;
  font-weight: 700;
}

.page-header p {
  margin: 0;
  font-size: 18px;
  opacity: 0.9;
}

.main-content {
  display: flex;
  gap: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.left-panel {
  flex-shrink: 0;
}

.center-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.test-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.test-section h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 15px;
}

.test-controls {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.test-results h4 {
  margin: 0 0 15px 0;
  color: #555;
  font-size: 16px;
  font-weight: 600;
}

.result-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.result-item .value {
  font-weight: 600;
  color: #2196f3;
}

.event-log {
  height: 300px;
  overflow-y: auto;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  border: 1px solid #e0e0e0;
}

.event-item {
  margin-bottom: 12px;
  padding: 10px;
  background: white;
  border-radius: 6px;
  border-left: 4px solid #e0e0e0;
}

.event-item.Connected {
  border-left-color: #4caf50;
}

.event-item.Reconnecting {
  border-left-color: #ff9800;
}

.event-item.Reconnected {
  border-left-color: #4caf50;
}

.event-item.Disconnected {
  border-left-color: #f44336;
}

.event-item.PlayerJoined {
  border-left-color: #2196f3;
}

.event-item.PlayerLeft {
  border-left-color: #ff9800;
}

.event-item.GameStarted {
  border-left-color: #4caf50;
}

.event-item.GameEnded {
  border-left-color: #ff9800;
}

.event-item.PaintActionReceived {
  border-left-color: #9c27b0;
}

.event-item.ChatMessage {
  border-left-color: #607d8b;
}

.event-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.event-type {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.event-time {
  font-size: 12px;
  color: #666;
}

.event-data {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #555;
  background: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
  white-space: pre-wrap;
  word-break: break-all;
}

.event-controls {
  display: flex;
  gap: 10px;
}

.right-panel {
  flex-shrink: 0;
  width: 300px;
}

.status-panel {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.status-panel h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 15px;
}

.status-section {
  margin-bottom: 25px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.status-section h4 {
  margin: 0 0 15px 0;
  color: #555;
  font-size: 16px;
  font-weight: 600;
}

.status-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 5px 0;
  font-size: 14px;
}

.status-item .value {
  font-weight: 600;
  color: #2196f3;
}

.status-item .value.error {
  color: #f44336;
}

.status-item .value.connected {
  color: #4caf50;
}

.status-item .value.connecting {
  color: #ff9800;
}

.status-item .value.disconnected {
  color: #f44336;
}

.status-item .value.waiting {
  color: #2196f3;
}

.status-item .value.playing {
  color: #4caf50;
}

.status-item .value.finished {
  color: #ff9800;
}

.status-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 10px 20px;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.status-item {
  display: flex;
  gap: 10px;
  align-items: center;
}

.status-item .value {
  font-weight: 600;
  color: #4caf50;
}

.status-item .value.connected {
  color: #4caf50;
}

.status-item .value.connecting {
  color: #ff9800;
}

.status-item .value.disconnected {
  color: #f44336;
}

.status-item .value.reconnecting {
  color: #ff9800;
}

/* 滚动条样式 */
.event-log::-webkit-scrollbar {
  width: 6px;
}

.event-log::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.event-log::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.event-log::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    flex-direction: column;
    align-items: center;
  }
  
  .left-panel,
  .right-panel {
    width: 100%;
    max-width: 400px;
  }
}

@media (max-width: 768px) {
  .realtime-test-page {
    padding: 10px;
  }
  
  .page-header h1 {
    font-size: 28px;
  }
  
  .page-header p {
    font-size: 16px;
  }
  
  .test-controls {
    flex-direction: column;
  }
  
  .test-controls .el-button {
    width: 100%;
  }
}

.canvas-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.paint-canvas {
  border: 2px solid #ddd;
  border-radius: 8px;
  cursor: crosshair;
  background: white;
}

.canvas-controls {
  display: flex;
  gap: 15px;
  align-items: center;
  justify-content: center;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
  width: 100%;
}

.canvas-sync-test {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.canvas-sync-test h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 1.2rem;
}

.canvas-sync-test .test-controls {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.canvas-sync-test .canvas-comparison {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  justify-content: center;
}

.canvas-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.canvas-section h4 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.test-canvas {
  border: 2px solid #ddd;
  border-radius: 8px;
  cursor: crosshair;
  background: white;
}

.local-canvas {
  border-color: #1890ff;
}

.sync-canvas {
  border-color: #52c41a;
}

.canvas-stats {
  background: #f8f9fa;
  padding: 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
  text-align: center;
}

.canvas-stats p {
  margin: 2px 0;
}

.sync-controls {
  display: flex;
  gap: 20px;
  justify-content: center;
  margin-bottom: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.sync-controls .control-group {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.sync-controls label {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.canvas-sync-test .debug-info {
  background: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 15px;
}

.canvas-sync-test .debug-info p {
  margin: 5px 0;
  font-size: 12px;
  color: #666;
}

.canvas-sync-test .event-log {
  max-height: 200px;
  overflow-y: auto;
  background: #f8f9fa;
  border-radius: 4px;
  padding: 10px;
}

.canvas-sync-test .event-log h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #333;
}

.canvas-sync-test .event-item {
  display: flex;
  gap: 10px;
  margin-bottom: 5px;
  font-size: 11px;
  color: #666;
}

.canvas-sync-test .event-time {
  color: #999;
  min-width: 60px;
}

.canvas-sync-test .event-type {
  color: #2196f3;
  font-weight: 600;
  min-width: 80px;
}

.canvas-sync-test .event-data {
  flex: 1;
  word-break: break-all;
}
</style>
